﻿using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class FashionPartModelProcessor : AssetPostprocessor
{
    static bool _autoBuildPrefab = true;
    public static bool autoBuildPrefab { get { return _autoBuildPrefab; } set { _autoBuildPrefab = value; } }
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        if (autoBuildPrefab)
        {
            foreach (var p in importedAssets)
            {
                BuildPrefab(p, false);
            }
        }
    }
    static public void BuildPrefab(string assetPath)
    {
        BuildPrefab(assetPath, true);
    }
    static void BuildPrefab(string assetPath, bool forceBuild)
    {
        if (assetPath.Contains("@")
            || !assetPath.EndsWith(".fbx", System.StringComparison.OrdinalIgnoreCase))
            return;
        string prefabPath = Path.ChangeExtension(assetPath,".prefab");
        if (!forceBuild && File.Exists(prefabPath))
            return;

        var obj = AssetDatabase.LoadAssetAtPath(assetPath,typeof(GameObject));
        var go = GameObject.Instantiate(obj) as GameObject;
        
        var animator = go.GetComponent<Animator>();
        if (null != animator)
            GameObject.DestroyImmediate(animator);
        foreach (SkinnedMeshRenderer smr in go.GetComponentsInChildren<SkinnedMeshRenderer>())
        {
            smr.quality = SkinQuality.Bone2;
            smr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            smr.receiveShadows = false;
        }

        AssetDatabase.DeleteAsset(prefabPath);

        PrefabUtility.CreatePrefab(prefabPath,go);

        GameObject.DestroyImmediate(go);
        AssetDatabase.SaveAssets();
    }
    public Material OnAssignMaterialModel(Material m, Renderer r)
    {
        ModelImporter mi = assetImporter as ModelImporter;
        //mi.importMaterials = false;
        if (mi != null && !mi.importMaterials && m.shader.name == "Standard")
        {
            Material emptyMaterial = AssetDatabase.LoadAssetAtPath<Material>("Assets/EmptyMaterial.mat");
            if (emptyMaterial == null)
            {
            }
            return emptyMaterial;
        }
        return null;
    }
}